<?php
require_once('../../core.inc.php');
require_once('Model/SiteManage.php');
require_once('View/Smarty.php');
require_once('Model/DB.php');
require_once('Model/Validate.php');
require_once('Model/Pager.php');
require_once('Model/Uploader.php');
require_once('Plugin/Item.php');

$sys = new Model_SiteManage();
$sys->checkLogin();
$params = $_REQUEST;
$smarty = new View_Smarty($params);
$item   = new Model_Item();
$smarty->assign('item', $item);
//var_dump($params);exit;
if (isset($params['do']) && function_exists('exec_' . $params['do'])){
   $params['op'] = call_user_func('exec_' . $params['do'], &$params, &$smarty, &$item);
}
if (isset($params['op']) && function_exists('op_' . $params['op'])){
    call_user_func('op_' . $params['op'], $params, &$smarty, &$item);
}
else{
    call_user_func('op_search', $params, &$smarty, &$item);
}
//
// 検索・一覧
function op_search($params, &$smarty, &$item)
{
    if (!isset($params['search'])){
        $params['search']   = array();
    }else{
        $page_id = isset($params['page_id']) && $params['page_id'] > 1 ? $params['page_id'] : 1;
        $max_row = 20;
        $pager   = new Model_Pager();
        $pager->getPagerInfo($item->getListCount($params['search']), $page_id, $max_row);
        $list = $item->getList($params['search'], 'id DESC', $max_row, ($max_row * ($page_id - 1)));
        $smarty->assign('list', $list);
        $smarty->assign('pager', $pager);
    }
    $smarty->assign('status', $item->getStatusMap());
    $smarty->assign('search', $params['search']);
    $smarty->display('item/item_index.html');
}
// 新規登録
function op_regist($params, &$smarty, &$item)
{
    if (!isset($params['forms'])){
        $forms = array();
        foreach($item->getFormKeys() as $key){
            $forms[$key] = '';
        }
        $forms["status"] = 2;
        $params['forms'] = $forms;
        
        $image_list[1] = array("");//画像
    }
    else
    {
        foreach($params["image"] as $num => $one)
        {
            $image_list[$num] = $one;
        }

        if($params["mode"] == "add_img")//画像枠を追加
        {
            $image_list[$num+1] = array();
        }

        if(isset($params["del_num"]))//画像削除
        {
            if(count($image_list) > 1)
                unset($image_list[$params["del_num"]]);
            else
                $image_list[$params["del_num"]] = array("");
        }
    }
    
    global $sys;
    if ($sys->isValidPlugin('MANAGE_CATEGORY')){
        $setting = $item->getSetting();
        $smarty->assign('use_category', $setting['category_id']);
    }
    
    $smarty->assign('image_list', $image_list);
    $smarty->assign('phase', 'input');
    $smarty->assign('forms', $params['forms']);
    $smarty->display('item/item_form.html');
}
function exec_validate_regist_form(&$params, &$smarty, &$item)
{
    $err = array();

    if($params["mode"] != "add_img" and $params["mode"] != "remove_img")
    {
        if($item->validate($params['forms'], $err)){
            return exec_regist_form($params, $smarty, $item);
        }
    }
        
    $validate = new Model_Validate();
    $smarty->assign('validate', $validate);
    $smarty->assign('err', $err);
    return 'regist';
}
function exec_regist_form(&$params, &$smarty, &$item)
{
    $params['forms']['st_time'] = $params['forms']['st_date'].' '.$params['forms']['st_time'];
    $params['forms']['ed_time'] = $params['forms']['ed_date'].' '.$params['forms']['ed_time'];
    $params['forms']['sp_st_time'] = $params['forms']['sp_st_date'].' '.$params['forms']['sp_st_time'];
    $params['forms']['sp_ed_time'] = $params['forms']['sp_ed_date'].' '.$params['forms']['sp_ed_time'];
    $id = $item->insert($params['forms']);

    $item->updateCategory($id, $params['forms']['select_category']);
    $item->registItemImage($id, $params["image"]);
    header('Location: '. $_SERVER['SCRIPT_NAME'] . '?op=regist_complete&id=' . $id);
    exit();
}
function op_regist_complete($params, &$smarty, &$item)
{
    $smarty->assign('phase', 'complete');
    if(isset($params['id'])){
        $smarty->assign('id', $params['id']);
        $forms = $item->get($params['id']);
        $smarty->assign('forms', $forms);
    }
    $smarty->assign('message', '登録が完了しました');
    $smarty->display('item/item_form.html');
}
// 編集
function op_edit($params, &$smarty, &$item)
{
    if (!isset($params['id'])){
        __raise_error();
    }
    $id = $params['id'];
    if (!isset($params['forms'])){
        $forms = $item->get($id);

        if($forms['st_time'] != '0000-00-00 00:00:00'){
            $forms['st_date'] = date('Y-m-d', strtotime($forms['st_time']));
            $forms['st_time'] = date('G', strtotime($forms['st_time']));
        }
        if($forms['ed_time'] != '0000-00-00 00:00:00'){
            $forms['ed_date'] = date('Y-m-d', strtotime($forms['ed_time']));
            $forms['ed_time'] = date('G', strtotime($forms['ed_time']));
        }
        if($forms['sp_st_time'] != '0000-00-00 00:00:00'){
            $forms['sp_st_date'] = date('Y-m-d', strtotime($forms['sp_st_time']));
            $forms['sp_st_time'] = date('G', strtotime($forms['sp_st_time']));
        }
        if($forms['sp_ed_time'] != '0000-00-00 00:00:00'){
            $forms['sp_ed_date'] = date('Y-m-d', strtotime($forms['sp_ed_time']));
            $forms['sp_ed_time'] = date('G', strtotime($forms['sp_ed_time']));
        }
        $params['forms'] = $forms;
        
        //画像
        $db = new Model_DB();
        $sql = sprintf("SELECT * FROM D_IMAGE WHERE func = %u and id = %u ORDER BY order_num", $item->config['id'], $forms['id'] );
        $db->query( $sql );
        if( $db->num_rows() ){
            while( $row = $db->fetch() ){
                $image_list[$row['order_num']] = array($item->getThumbDir().$row['filename']);
            }
        }
        else
        {
            $image_list[1] = array("");
        }
    }
    else
    {
        foreach($params["image"] as $num => $one)
        {
            $image_list[$num] = $one;
        }
        
        if($params["mode"] == "add_img")//画像枠を追加
        {
            $image_list[$num+1] = array();
        }
        //var_dump($params);exit;
        if(isset($params["del_num"]))//画像削除
        {
            if(count($image_list) > 1)
                unset($image_list[$params["del_num"]]);
            else
                $image_list[$params["del_num"]] = array("");
        }
    }
    global $sys;
    if ($sys->isValidPlugin('MANAGE_CATEGORY')){
        $setting = $item->getSetting();
        $smarty->assign('use_category', $setting['category_id']);
        $params['forms']['select_category'] = $item->getCategory($id);
    }
    $smarty->assign('id', $id);
    $smarty->assign('image_list', $image_list);
    $smarty->assign('phase', 'input');
    $smarty->assign('forms', $params['forms']);
    $smarty->display('item/item_form.html');
}
function exec_validate_edit_form(&$params, &$smarty, &$item)
{
    if (!isset($params['id'])){
        __raise_error();
    }
    if ($params['mode'] == 'delete')
    {
        return exec_delete_form($params, $smarty, $item);
    }
    $err = array();
    
    if($params["mode"] != "add_img" and $params["mode"] != "remove_img")
    {
        if ($item->validate($params['forms'], $err)){
            return exec_edit_form($params, $smarty, $item);
        }
    }
    $validate = new Model_Validate();
    $smarty->assign('validate', $validate);
    $smarty->assign('err', $err);
    return 'edit';
}
function exec_edit_form(&$params, &$smarty, &$item)
{
    if (!isset($params['id'])){
        __raise_error();
    }
    $id = $params['id'];   
    $params['forms']['st_time'] = $params['forms']['st_date'].' '.$params['forms']['st_time'];
    $params['forms']['ed_time'] = $params['forms']['ed_date'].' '.$params['forms']['ed_time'];
    $params['forms']['sp_st_time'] = $params['forms']['sp_st_date'].' '.$params['forms']['sp_st_time'];
    $params['forms']['sp_ed_time'] = $params['forms']['sp_ed_date'].' '.$params['forms']['sp_ed_time'];
    $item->update($id, $params['forms']);
    $uploader  = new Model_Uploader();

    $item->updateCategory($id, $params['forms']['select_category']);
    $item->registItemImage($id, $params["image"]);
    header('Location: '. $_SERVER['SCRIPT_NAME'] . '?op=edit_complete&id=' . $id);
    exit();
}
function op_edit_complete($params, &$smarty, &$item)
{
    $smarty->assign('phase', 'complete');
    if(isset($params['id'])){
        $smarty->assign('id', $params['id']);
    }
    $smarty->assign('message', '更新が完了しました');
    $smarty->display('item/item_form.html');
}
//　削除
function exec_delete_form(&$params, &$smarty, &$item)
{
    if (!isset($params['id'])){
        __raise_error();
    }
    $row = $item->get($params['id']);
    $res = $item->delete($params['id']);
    if($res){
        if( $row['file1'] != '' ){
            $result = unlink( $item->getSiteDir().'images/' . $row['file1'] );
        }
        if( $row['file2'] != '' ){
            unlink( $item->getSiteDir().'images/' . $row['file2'] );
        }
        $item->updateCategory($id, array());
    }
    header('Location: '. $_SERVER['SCRIPT_NAME'] . '?op=delete_complete&id=' . $id);
    exit();
}
function op_delete_complete($params, &$smarty, &$item)
{
    $smarty->assign('phase', 'complete');
    $smarty->assign('message', '削除が完了しました');
    $smarty->display('item/item_form.html');
}
// 基本設定
function op_setting($params, &$smarty, &$item)
{
    if (!isset($params['forms'])){
        $params['forms'] = $item->getSetting();
    }
    global $sys;
    if ($sys->isValidPlugin('MANAGE_CATEGORY')){
        require_once('Plugin/Category.php');
        $category = new Model_Category();
        $list = $category->getList(array('parent' => 1, 'site_id' => $sys->getCurrentSite()));
        foreach($list as $one)
        {
            $category_list[$one['id']] = $one['category_name'];
        }
        $smarty->assign('category_list', $category_list);
    }
    
    $db = new Model_DB();
    $sql = sprintf("SELECT RC.category
                    FROM R_COMPANY RC
                    WHERE RC.func = %u ", $item->config['id']);
    $db->query( $sql );
    if( $db->num_rows() ){
        while( $row = $db->fetch() ){
            $select_category[] = $row['category'];
        }
        $params['forms']['select_category'] = $select_category;
    }
    
    $smarty->assign('phase', 'input');
    $smarty->assign('forms', $params['forms']);
    $smarty->display('item/item_setting.html');
}
function exec_validate_setting_form(&$params, &$smarty, &$item)
{
    $err = array();
    if ($item->validateSetting($params['forms'], $err)){
        return exec_setting_form($params, $smarty, $item);
    }
    $validate = new Model_Validate();
    $smarty->assign('validate', $validate);
    $smarty->assign('err', $err);
    return 'setting';
}
function exec_setting_form(&$params, &$smarty, &$item)
{
    if (empty($params['forms']['category_id'])){
        $params['forms']['category_id'] = '0';    // default
    }
    $params['forms']['top_items']  = implode(',', $params['forms']['top_items']);
    $params['forms']['list_items'] = implode(',', $params['forms']['list_items']);
    $item->updateSetting($params['forms']);
    $item->updateCompany($params['forms']['select_category']);
    header('Location: '. $_SERVER['SCRIPT_NAME'] . '?op=setting_complete');
    exit();
}
function op_setting_complete($params, &$smarty, &$item)
{
    $smarty->assign('phase', 'complete');
    $smarty->assign('message', '設定が完了しました');
    $smarty->display('item/item_setting.html');
}


// 表示設定
function op_rank($params, &$smarty, &$item)
{
    if (!isset($params['forms'])){
        $setting = $item->getSetting();
        $category_id = $setting['category_id'];
    }
    global $sys;
    if ($sys->isValidPlugin('MANAGE_CATEGORY')){
        require_once('Plugin/Category.php');
        $category = new Model_Category();
        $list = $category->getList(array('parent' => $category_id, 'site_id' => $sys->getCurrentSite()));
        foreach($list as $one)
        {
            $category_list[$one['id']] = $one['category_name'];
        }
        $smarty->assign('category_list', $category_list);
    }
    $smarty->assign('phase', 'input');
    $smarty->assign('forms', $params['forms']);
    $smarty->display('item/item_rank.html');
}
// 表示設定入力
function op_rankform($params, &$smarty, &$item)
{
    if (!isset($params['category_id']) or !isset($params['type'])){
        __raise_error();
    }
    
    $db = new Model_DB();
    $category_id = $params['category_id'];
    $type = $params['type'];//1: おすすめ  2:ランキング
    
    for( $i = 1; $i <= 10; $i++ ){
            $data[$i]['id'] = '';
            $data[$i]['item_name'] = '';
    }
    
    $sql = sprintf("SELECT I.id, I.item_name, R.rank FROM D_ITEM_RANK R, M_ITEM I WHERE R.category_id = %u AND R.type = %u AND R.item_id = I.id" , $category_id, $type );
    $db->query( $sql );
    if( $db->num_rows() ){
        while( $row = $db->fetch() ){
            $data[$row['rank']]['id'] = $row['id'];
            $data[$row['rank']]['item_name'] = $row['item_name'];
        }
    }

    $sql = sprintf("SELECT comment FROM D_ITEM_RANK WHERE category_id = %u AND type = %u AND rank = 0" , $category_id, $type );
    $db->query( $sql );
    if( $db->num_rows() ){
        $row = $db->fetch();
        $forms['comment'] = $row['comment'];
    }else{
        $forms['comment'] = '';
    }
    

    /*
    if (!isset($params['forms'])){
        $setting = $item->getSetting();
        $category_id = $setting['category_id'];
    }
    global $sys;
    if ($sys->isValidPlugin('MANAGE_CATEGORY')){
        require_once('Plugin/Category.php');
        $category = new Model_Category();
        $list = $category->getList(array('parent' => $category_id, 'site_id' => $sys->getCurrentSite()));
        foreach($list as $one)
        {
            $category_list[$one['id']] = $one['category_name'];
        }
        $smarty->assign('category_list', $category_list);
    }
     * 
     */
    $smarty->assign('phase', 'input');
    $smarty->assign('data', $data);
    $smarty->assign('forms', $forms);
    $smarty->display('item/item_rankform.html');
}

function exec_validate_rank_form(&$params, &$smarty, &$item)
{
    $err = array();
    return exec_rank_form($params, $smarty, $item);
//    if ($item->validateSetting($params['forms'], $err)){
//        return exec_rank_form($params, $smarty, $item);
//    }
    $validate = new Model_Validate();
    $smarty->assign('validate', $validate);
    $smarty->assign('err', $err);
    return 'rank';
}
function exec_rank_form(&$params, &$smarty, &$item)
{
    $sql = sprintf("DELETE FROM D_ITEM_RANK WHERE category_id = %u AND type = %u", $params['forms']['category_id'], $params['forms']['type'] );
    echo $sql;exit;
    $db->query( $sql );

    foreach( $forms['item_id'] as $k => $v )
    {
        if( $v != '' && is_numeric( $v ) ){
                $sql = sprintf( "INSERT INTO D_ITEM_RANK( category_id, type, item_id, rank ) VALUES( %u, %u, %u, %u )",
                        $forms['id'],
                        $forms['type'],
                        $v,
                        $k
                );
                $db->query( $sql );
        }
    }
    // コメント挿入
    $sql = sprintf("INSERT INTO D_ITEM_RANK( category_id, type, item_id, rank, comment ) VALUES( %u, %u, 0, 0, '%s' )",
            $params['forms']['category_id'],
            $params['forms']['type'],
            $db->escape( $params['forms']['comment'] )
    );
    $db->query( $sql );
    
    header('Location: '. $_SERVER['SCRIPT_NAME'] . '?op=rank_complete');
    exit();
}
function op_rank_complete($params, &$smarty, &$item)
{
    $smarty->assign('phase', 'complete');
    $smarty->assign('message', '設定が完了しました');
    $smarty->display('item/item_rankform.html');
}
// カテゴリ選択
function op_select_item($params, &$smarty, &$item)
{
    $category_id = $params['category_id'];

    $db = new Model_DB;

    if( $category_id == 0 ){
            $sql = "SELECT * FROM M_ITEM";
    }else{
            $sql = sprintf( "SELECT * FROM M_ITEM WHERE id IN (SELECT item_id FROM D_ITEM_CATEGORY WHERE category_id = %u )", $category_id );
    }
    $db->query( $sql );
    $data = array();
    if( $db->num_rows() ){
            while( $row = $db->fetch() ){
                    $data[] = $row;
            }
    }

    $smarty->assign('data', $data );
    $smarty->display('item/select_item.html');
}
?>